package com.jt.filter;

import org.apache.http.HttpHeaders;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 课堂练习:
 * 请求url黑名单过滤器,对请求url进行校验,合法则放行
 * 不合法抛异常
 */

@Component
public class BlackUrlGlobalFilter implements GlobalFilter, Ordered {

    //定义黑名单集合(在此集合中的url不允许访问我们的资源)
    private List<String> blackUrls = new ArrayList<>();

    public BlackUrlGlobalFilter (){
        blackUrls.add("/nacos/provider/echo/9002");
        blackUrls.add("/nacos/provider/echo/9003");
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //String path = exchange.getRequest().getURI().getPath();
        //1.获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.获取请求路径(不需要ip和端口)

        String path = request.getURI().getPath();
        System.out.println("URL=" + path);

        //3.判断请求路径是否是不允许的url
        if(blackUrls.contains(path)){
            System.out.println("黑名单!!!");
            //throw new RuntimeException("已加入黑名单~~~");
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE,"text/html;charset=utf8");
            String msg = "当前URL不允许访问资源";
            DataBuffer data = response.bufferFactory().wrap(msg.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(data));
            //return null;
        }
        return chain.filter(exchange);
    }

    /**
     * 定义过滤器的优先级,数字越小,优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
